import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:magma/heartbeat/helpers/magma_tap.dart';
import 'package:qlevar_router/qlevar_router.dart';
import 'package:stacked/stacked.dart';
import '../../heartbeat/helpers/magma_constant.dart';
import '../../heartbeat/helpers/magma_text_style.dart';
import '../../heartbeat/helpers/magma_color.dart';
import '../../heartbeat/helpers/magma_router.dart';
import '../../heartbeat/helpers/magma_toast.dart';
import '../../heartbeat/parts/login_required_dialog.dart';
import '../../heartbeat/parts/join_club_dialog.dart';
import '../../comms_link/app_state.dart';
import '../../heartbeat/blueprint/user_model.dart';
import '../../heartbeat/blueprint/club_model.dart';
import '../../heartbeat/blueprint/dynamic_model.dart';

/// 社区页面视图模型
class CommunityNavigatorViewModel extends BaseViewModel {
  /// 获取当前用户
  UserModel? get currentUser => appState.userStore.currentUser;

  /// 检查是否已登录
  bool get isLoggedIn => appState.userStore.isLoggedIn;

  /// 获取所有俱乐部
  List<ClubModel> get clubs => appState.clubManager.clubs;

  /// 获取所有动态
  List<ContentModel> get dynamics => appState.contentBroadcaster.dynamics;

  /// 初始化数据
  void initializeData() {
    notifyListeners();
  }

  /// 获取本周打卡记录
  List<WeeklyCheckinItem> getWeeklyCheckinItems() {
    final now = DateTime.now();
    final startOfWeek = now.subtract(Duration(days: now.weekday - 1));

    List<WeeklyCheckinItem> items = [];

    for (int i = 0; i < 7; i++) {
      final date = startOfWeek.add(Duration(days: i));
      final isToday =
          date.day == now.day &&
          date.month == now.month &&
          date.year == now.year;
      final isPast = date.isBefore(DateTime(now.year, now.month, now.day));

      String? checkinStatus;
      if (isLoggedIn && isPast) {
        final status = appState.checkinTracker.getUserCheckinStatus(
          currentUser!.id,
          date,
        );
        checkinStatus =
            status == true
                ? 'checked'
                : status == false
                ? 'unchecked'
                : null;
      }

      items.add(
        WeeklyCheckinItem(
          date: date,
          isToday: isToday,
          isPast: isPast,
          checkinStatus: checkinStatus,
        ),
      );
    }

    return items;
  }

  /// 获取用户信息
  UserModel? getUserById(String userId) {
    return appState.userStore.getUserById(userId);
  }

  /// 检查用户是否已加入俱乐部
  bool isUserMemberOfClub(String clubId) {
    if (!isLoggedIn) return false;
    return appState.clubManager.isUserMember(clubId, currentUser!.id);
  }

  /// 加入俱乐部
  Future<bool> joinClub(String clubId) async {
    if (!isLoggedIn) return false;
    final result = await appState.clubManager.enrollInClub(
      clubId: clubId,
      userId: currentUser!.id,
    );
    if (result) notifyListeners();
    return result;
  }

  /// 点赞动态
  Future<bool> toggleLike(String dynamicId) async {
    if (!isLoggedIn) return false;
    return await appState.contentBroadcaster.toggleAppreciation(
      dynamicId: dynamicId,
      userId: currentUser!.id,
    );
  }

  /// 检查用户是否已点赞
  bool hasUserLiked(String dynamicId) {
    if (!isLoggedIn) return false;
    return appState.contentBroadcaster.hasUserAppreciated(
      dynamicId,
      currentUser!.id,
    );
  }
}

/// 本周打卡记录项
class WeeklyCheckinItem {
  final DateTime date;
  final bool isToday;
  final bool isPast;
  final String? checkinStatus; // 'checked', 'unchecked', null

  WeeklyCheckinItem({
    required this.date,
    required this.isToday,
    required this.isPast,
    this.checkinStatus,
  });
}

/// 社区页面
class CommunityStory extends StatefulWidget {
  const CommunityStory({super.key});

  @override
  State<CommunityStory> createState() => _CommunityStoryState();
}

class _CommunityStoryState extends State<CommunityStory>
    with RouteAware, WidgetsBindingObserver {
  CommunityNavigatorViewModel? _viewModel;
  RouteObserver<ModalRoute<dynamic>>? _routeObserver;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // 订阅路由变化
    final route = ModalRoute.of(context);
    if (route != null && route is PageRoute) {
      _routeObserver = RouteObserver<ModalRoute<dynamic>>();
      _routeObserver!.subscribe(this, route);
    }
  }

  @override
  void dispose() {
    _routeObserver?.unsubscribe(this);
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didPopNext() {
    // 从其他页面返回到当前页面时触发
    super.didPopNext();
    if (_viewModel != null) {
      _viewModel!.initializeData();
    }
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    // 当应用恢复到前台时刷新数据
    if (state == AppLifecycleState.resumed && _viewModel != null) {
      _viewModel!.initializeData();
    }
  }

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<CommunityNavigatorViewModel>.reactive(
      viewModelBuilder: () => CommunityNavigatorViewModel(),
      onViewModelReady: (viewModel) {
        _viewModel = viewModel;
        viewModel.initializeData();
      },
      builder: (context, viewModel, child) {
        return Scaffold(
          backgroundColor: MagmaColor.black,
          body: Container(
            width: double.infinity,
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage(MagmaConstant.background),
                fit: BoxFit.cover,
              ),
            ),
            child: SafeArea(
              child: SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SizedBox(height: 16.h),

                    // 页面标题
                    Padding(
                      padding: EdgeInsets.symmetric(horizontal: 16.w),
                      child: Text(
                        'Daily Training',
                      ).blackHanSans(fontSize: 24.sp, color: MagmaColor.white),
                    ),

                    SizedBox(height: 16.h),

                    // 打卡盒子
                    _buildCheckinCard(context, viewModel),

                    SizedBox(height: 16.h),

                    // Marathon Club 标题
                    Padding(
                      padding: EdgeInsets.symmetric(horizontal: 16.w),
                      child: Text(
                        'Marathon Club',
                      ).blackHanSans(fontSize: 24.sp, color: MagmaColor.white),
                    ),

                    SizedBox(height: 16.h),

                    // 俱乐部列表
                    _buildClubList(viewModel),

                    SizedBox(height: 16.h),

                    // Discover 标题
                    Padding(
                      padding: EdgeInsets.symmetric(horizontal: 16.w),
                      child: Row(
                        children: [
                          Text('Discover').blackHanSans(
                            fontSize: 24.sp,
                            color: MagmaColor.white,
                          ),
                          Spacer(),
                          // 发布
                          MagmaTap(
                            onTap: () => QR.to(MagmaRouter.publishDynamicPath),
                            child: Image.asset(
                              MagmaConstant.publish,
                              width: 24.w,
                              height: 24.w,
                            ),
                          ),
                        ],
                      ),
                    ),

                    SizedBox(height: 16.h),

                    // 动态列表
                    _buildDynamicGrid(viewModel),

                    SizedBox(height: 120.h),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  /// 构建打卡卡片
  Widget _buildCheckinCard(
    BuildContext context,
    CommunityNavigatorViewModel viewModel,
  ) {
    return MagmaTap(
      onTap: () => QR.to(MagmaRouter.checkinPath),
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 16.w),
        child: AspectRatio(
          aspectRatio: 374 / 165,
          child: Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage(MagmaConstant.communityCheckCard),
                fit: BoxFit.cover,
              ),
            ),
            child: Padding(
              padding: EdgeInsets.all(16.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 描述文字
                  Text(
                    'Marathon daily training plan, scientific progress, making every step you take more effective!',
                    style: TextStyle(height: 1.38),
                  ).inter(
                    fontSize: 16.sp,
                    color: MagmaColor.black,
                    fontWeight: FontWeight.w400,
                  ),

                  SizedBox(height: 10.h),

                  // 本周打卡记录
                  Expanded(
                    child: Row(
                      children:
                          viewModel.getWeeklyCheckinItems().map((item) {
                            return Expanded(child: _buildCheckinDayItem(item));
                          }).toList(),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  /// 构建单个打卡日期项
  Widget _buildCheckinDayItem(WeeklyCheckinItem item) {
    return AspectRatio(
      aspectRatio: 50 / 63,
      child: Container(
        decoration: BoxDecoration(
          color: MagmaColor.black,
          borderRadius: BorderRadius.circular(12.r),
          border: Border.all(color: MagmaColor.white, width: 1.w),
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            // 日期或状态图标
            Center(child: _buildDayContent(item)),

            // 星期缩写
            Text(
              _getWeekdayAbbr(item.date.weekday),
              style: TextStyle(
                fontSize: 12.sp,
                color: Colors.white.withValues(alpha: 0.80),
                fontFamily:
                    GoogleFonts.racingSansOne(
                      fontWeight: FontWeight.w400,
                    ).fontFamily,
                fontWeight: FontWeight.w400,
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建日期内容
  Widget _buildDayContent(WeeklyCheckinItem item) {
    if (item.checkinStatus == 'checked') {
      return Image.asset(MagmaConstant.check, width: 20.w, height: 20.w);
    } else if (item.checkinStatus == 'unchecked') {
      return Image.asset(MagmaConstant.noCheck, width: 20.w, height: 20.w);
    } else {
      return Text(
        item.date.day.toString(),
        style: TextStyle(
          fontSize: 20.sp,
          color: MagmaColor.white,
          fontFamily:
              GoogleFonts.racingSansOne(fontWeight: FontWeight.w400).fontFamily,
          fontWeight: FontWeight.w400,
        ),
      );
    }
  }

  /// 获取星期缩写
  String _getWeekdayAbbr(int weekday) {
    const weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
    return weekdays[weekday - 1];
  }

  /// 构建俱乐部列表
  Widget _buildClubList(CommunityNavigatorViewModel viewModel) {
    return SizedBox(
      height: 188.h,
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        padding: EdgeInsets.symmetric(horizontal: 20.w),
        itemCount: viewModel.clubs.length,
        itemBuilder: (context, index) {
          final club = viewModel.clubs[index];
          return _buildClubCard(club, viewModel);
        },
      ),
    );
  }

  /// 构建俱乐部卡片
  Widget _buildClubCard(ClubModel club, CommunityNavigatorViewModel viewModel) {
    return Container(
      width: 350.w,
      margin: EdgeInsets.only(right: 16.w),
      child: AspectRatio(
        aspectRatio: 350 / 188,
        child: Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage(MagmaConstant.communityClubCard),
              fit: BoxFit.cover,
            ),
          ),
          child: Row(
            children: [
              // 俱乐部图片
              AspectRatio(
                aspectRatio: 146 / 191,
                child: Container(
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage(club.image),
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
              ),

              // 俱乐部信息
              Expanded(
                child: Padding(
                  padding: EdgeInsets.all(10.w),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 创建者头像和名称
                      Row(
                        children: [
                          CircleAvatar(
                            radius: 16.r,
                            backgroundImage: AssetImage(
                              viewModel.getUserById(club.creatorId)?.avatar ??
                                  MagmaConstant.avatar1,
                            ),
                          ),
                          SizedBox(width: 8.w),
                          Text(
                            viewModel.getUserById(club.creatorId)?.username ??
                                'Unknown',
                          ).blackHanSans(
                            fontSize: 14.sp,
                            color: MagmaColor.black,
                            fontWeight: FontWeight.w400,
                          ),
                          Spacer(),
                          Text(
                            '${club.currentMembers}/${club.maxMembers}',
                          ).inter(
                            fontSize: 16.sp,
                            color: MagmaColor.black,
                            fontWeight: FontWeight.w500,
                          ),
                        ],
                      ),

                      SizedBox(height: 8.h),

                      // 俱乐部描述
                      Text(club.description, maxLines: 3).inter(
                        fontSize: 16.sp,
                        color: MagmaColor.black,
                        fontWeight: FontWeight.w600,
                      ),

                      Spacer(),

                      // 成员头像和加入按钮
                      Row(
                        children: [
                          // 叠层显示的成员头像
                          SizedBox(
                            width: 100.w,
                            height: 28.h,
                            child: Stack(
                              children: [
                                ...club.memberIds
                                    .take(3)
                                    .toList()
                                    .asMap()
                                    .entries
                                    .map((entry) {
                                      final index = entry.key;
                                      final memberId = entry.value;
                                      return Positioned(
                                        left: (index * 20).w,
                                        child: Container(
                                          decoration: BoxDecoration(
                                            shape: BoxShape.circle,
                                            border: Border.all(
                                              color: MagmaColor.black,
                                              width: 1.w,
                                            ),
                                          ),
                                          child: CircleAvatar(
                                            radius: 12.r,
                                            backgroundImage: AssetImage(
                                              viewModel
                                                      .getUserById(memberId)
                                                      ?.avatar ??
                                                  MagmaConstant.avatar1,
                                            ),
                                          ),
                                        ),
                                      );
                                    }),
                                if (club.memberIds.length > 3)
                                  Positioned(
                                    left: (3 * 20).w,
                                    child: ClipRRect(
                                      borderRadius: BorderRadius.circular(12.r),
                                      child: BackdropFilter(
                                        filter: ImageFilter.blur(
                                          sigmaX: 10,
                                          sigmaY: 10,
                                        ),
                                        child: Container(
                                          decoration: BoxDecoration(
                                            shape: BoxShape.circle,
                                            border: Border.all(
                                              color: MagmaColor.black,
                                              width: 1.w,
                                            ),
                                          ),
                                          child: CircleAvatar(
                                            radius: 12.r,
                                            backgroundColor: MagmaColor.white
                                                .withValues(alpha: 0.50),
                                            child: Text(
                                              '+${club.memberIds.length - 3}',
                                            ).blackHanSans(
                                              fontSize: 12.sp,
                                              color: MagmaColor.black,
                                              fontWeight: FontWeight.w400,
                                            ),
                                          ),
                                        ),
                                      ),
                                    ),
                                  ),
                              ],
                            ),
                          ),

                          Spacer(),

                          // 加入/聊天按钮
                          StatefulBuilder(
                            builder: (context, setState) {
                              final isMember = viewModel.isUserMemberOfClub(
                                club.id,
                              );

                              return MagmaTap(
                                onTap: () async {
                                  // 检查登录状态
                                  if (!viewModel.isLoggedIn) {
                                    await LoginRequiredDialog.show(context);
                                    return;
                                  }

                                  if (isMember) {
                                    // 前往聊天页面
                                    QR.to(
                                      MagmaRouter.groupChatPath.replaceAll(
                                        ':clubId',
                                        club.id,
                                      ),
                                    );
                                  } else {
                                    // 显示加入确认对话框
                                    final result = await JoinClubDialog.show(
                                      context,
                                      clubName: club.name,
                                    );

                                    if (result == true) {
                                      final joinResult = await viewModel
                                          .joinClub(club.id);

                                      if (joinResult) {
                                        setState(() {});
                                        if (context.mounted) {
                                          MagmaToast.success(
                                            context,
                                            title:
                                                'Successfully joined ${club.name}',
                                          );
                                        }
                                      }
                                    }
                                  }
                                },
                                child: Container(
                                  width: 80.w,
                                  height: 32.h,
                                  decoration: BoxDecoration(
                                    color: MagmaColor.purple,
                                    borderRadius: BorderRadius.circular(16.r),
                                  ),
                                  child: Center(
                                    child: Text(
                                      isMember ? 'Chat' : 'Join In',
                                    ).blackHanSans(
                                      fontSize: 14.sp,
                                      color: MagmaColor.black,
                                      fontWeight: FontWeight.w600,
                                    ),
                                  ),
                                ),
                              );
                            },
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建动态网格
  Widget _buildDynamicGrid(CommunityNavigatorViewModel viewModel) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      child: GridView.builder(
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          crossAxisSpacing: 12.w,
          mainAxisSpacing: 12.h,
          childAspectRatio: 182 / 272,
        ),
        itemCount: viewModel.dynamics.length,
        itemBuilder: (context, index) {
          final dynamic = viewModel.dynamics[index];
          return _buildDynamicCard(dynamic, viewModel, index);
        },
      ),
    );
  }

  /// 构建动态卡片
  Widget _buildDynamicCard(
    ContentModel dynamic,
    CommunityNavigatorViewModel viewModel,
    int index,
  ) {
    final isLeftColumn = index % 2 == 0;
    final backgroundImage =
        isLeftColumn
            ? MagmaConstant.dynamicCardLeft
            : MagmaConstant.dynamicCardRight;

    return MagmaTap(
      onTap: () {
        QR.to(
          MagmaRouter.dynamicDetailPath.replaceAll(':dynamicId', dynamic.id),
        );
      },
      child: AspectRatio(
        aspectRatio: 182 / 272,
        child: Stack(
          clipBehavior: Clip.none,
          children: [
            Container(
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage(backgroundImage),
                  fit: BoxFit.cover,
                ),
                borderRadius: BorderRadius.circular(2.r),
              ),
              child: Padding(
                padding: EdgeInsets.all(6.w),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 动态图片
                    Expanded(
                      flex: 6,
                      child: Stack(
                        clipBehavior: Clip.none,
                        children: [
                          Container(
                            width: double.infinity,
                            decoration: BoxDecoration(
                              image: DecorationImage(
                                image: AssetImage(
                                  dynamic.imagePath ??
                                      dynamic.coverImagePath ??
                                      MagmaConstant.dynamic1,
                                ),
                                fit: BoxFit.cover,
                              ),
                            ),
                          ),
                          // 播放图标（仅视频类型显示）
                          if (dynamic.type == ContentType.video)
                            Center(
                              child: Icon(
                                Icons.play_arrow,
                                color: Colors.white,
                                size: 36.w,
                              ),
                            ),
                          // 白色三角形（仅在左列显示）
                          if (isLeftColumn)
                            Positioned(
                              top: 0,
                              left: 0,
                              child: Image.asset(
                                MagmaConstant.triangle,
                                width: 18.w,
                                height: 18.w,
                                color: Colors.white,
                              ),
                            ),
                        ],
                      ),
                    ),

                    SizedBox(height: 12.h),

                    // 动态标题
                    Expanded(
                      flex: 2,
                      child: Text(
                        dynamic.title,
                        maxLines: 3,
                        overflow: TextOverflow.ellipsis,
                      ).blackHanSans(
                        fontSize: 12.sp,
                        color: MagmaColor.black,
                        fontWeight: FontWeight.w400,
                      ),
                    ),

                    // 创建者和点赞
                    Expanded(
                      flex: 1,
                      child: StatefulBuilder(
                        builder: (context, setState) {
                          final isLiked = viewModel.hasUserLiked(dynamic.id);

                          return Row(
                            children: [
                              CircleAvatar(
                                radius: 14.r,
                                backgroundImage: AssetImage(
                                  viewModel
                                          .getUserById(dynamic.userId)
                                          ?.avatar ??
                                      MagmaConstant.avatar1,
                                ),
                              ),
                              SizedBox(width: 6.w),
                              Expanded(
                                child: Text(
                                  viewModel
                                          .getUserById(dynamic.userId)
                                          ?.username ??
                                      'Unknown',
                                ).inter(
                                  fontSize: 12.sp,
                                  color: MagmaColor.black,
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                              MagmaTap(
                                onTap: () async {
                                  // 检查是否登录
                                  if (!viewModel.isLoggedIn) {
                                    await LoginRequiredDialog.show(context);
                                    return;
                                  }

                                  // 保存当前点赞状态
                                  final wasLiked = isLiked;

                                  // 切换点赞状态
                                  final result = await viewModel.toggleLike(
                                    dynamic.id,
                                  );

                                  if (result) {
                                    // 局部刷新当前卡片
                                    setState(() {});

                                    // 显示成功提示
                                    if (context.mounted) {
                                      MagmaToast.success(
                                        context,
                                        title: wasLiked ? 'Unliked' : 'Liked',
                                      );
                                    }
                                  }
                                },
                                child: Image.asset(
                                  MagmaConstant.like,
                                  width: 20.w,
                                  height: 20.w,
                                  color:
                                      isLiked ? Colors.red : MagmaColor.black,
                                ),
                              ),
                            ],
                          );
                        },
                      ),
                    ),
                  ],
                ),
              ),
            ),
            // 三角形图片（仅在左列显示）
            if (isLeftColumn)
              Positioned(
                top: -6.w,
                left: -6.w,
                child: Image.asset(
                  MagmaConstant.triangle,
                  width: 30.w,
                  height: 30.w,
                ),
              ),
          ],
        ),
      ),
    );
  }
}
